import Quene
from DATA import stockDATA
from fund import FUND


"""

策略类

"""













class STRATEGY:


    def __init__(self,**params):

        self.data=stockDATA(['2017-01-01',''],'SZ.002594','d',**{'stockCodeItems':'date,close'}).getData()
        print(self.data)
        self.money=FUND(50000)
        """策略参数"""
        self.params=params

        """买入 佣金加过户费"""
        self.taxbuy=0.00025+0.0002
        """卖出 佣金+过户费+印花税"""
        self.taxsell=0.00025+0.0002+0.001

        """本次触发买入卖出时间，方便记录histroy"""
        self.actime=''
        self.stockhave=0

        self.assethistroy={}
        """
        策略方法，
        遍历datalist 上的时间节点
        调用buy（）或者sell（）方法
        
        
        """
    def run(self):



        dataList={}
        for i in self.data:
            dataList[i[0]]=i[1]

        print(dataList)
        # res 计算方式为res7
        if self.params['res']==7 :
            lastprice = float(self.data[0][1])

            resup = Quene.Queue(self.params['res'])
            resdown = Quene.Queue(self.params['res'])


            for i in self.data:
                self.actime=i[0]
                currentprice=float(i[1])

                """当前时间节点下相对强弱指标"""
                res=round(currentprice-lastprice,2)
                lastprice=currentprice
                """大于0为上升指标指标"""
                if res>=0:
                    resup.enqueue(res)
                    if resup.size() + resdown.size() > self.params['res']:
                        resup.dequeue()
                else:          # 小于0为下降指标
                    resdown.enqueue(res)
                    if resup.size() + resdown.size() > self.params['res']:
                        resdown.dequeue()

                # 当达到7天周期时计算res指标
                if resup.size()+resdown.size()>=self.params['res']:

                    resrate=(resup.sum()/(resup.sum()+abs(resdown.sum())))*100
                    #小于30买入
                    if resrate<30:
                        # amount 购买数量
                        amount=int(self.money.count/(currentprice*(1+self.taxbuy))/100)*100
                        self.buy(amount,currentprice)


                    # 大于70卖出
                    if resrate>70:
                        # 全部卖出
                        amount = self.stockhave
                        if amount !=0:
                            self.sell(amount,currentprice)
                self.assethistroy[ self.actime]=self.money.count+self.stockhave+currentprice






    """
    :param 价格 数量 时间
    """
    def buy(self,amount,price):
        self.stockhave=amount+self.stockhave
        self.money.reduce(amount*price*(1+self.taxbuy),self.actime)

    """
        :param 价格 数量 时间
        """
    def sell(self,amount,price):
        self.stockhave = self.stockhave-amount
        self.money.add(amount*price*(1+self.taxbuy),self.actime)


    def showmoney(self):

        return self.money.history



    """返回总资产历史记录 包含现金加股票"""
    def showasset(self):
        return self.assethistroy

